import React from 'react';
import {inject, observer} from 'mobx-react';
import { WeaDialog,WeaNewScroll,WeaTools,WeaSelect,WeaInput,WeaUpload,WeaRightMenu } from 'ecCom';
import {Button,Spin,Modal,Row,Col,Checkbox} from 'antd';
import Collapse from '../workPlanCreate/collapse.js'
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const ButtonGroup = Button.Group;
const CheckboxGroup = Checkbox.Group;
import {toJS } from 'mobx';

@inject('myWorkPlanStore')
@observer
class WorkPlanImport extends React.Component {
  constructor(props) {
		super(props);
		this.state={
      optionsWorkPlanType:[],
      secretLevelOption:[],
      isOpenSecret:false,
			remindTypes:[],
      spinning:false,
      showChk:false,
			params:{
				remindType:[],
        workPlanType:'0',
        secretLevel:'4',
				validateType:'lastname',
				remindBeforeStart:false,
				remindDateBeforeStart:0,
				remindTimeBeforeStart:10,
				remindBeforeEnd:false,
				remindDateBeforeEnd:0,
				remindTimeBeforeEnd:10,
				excelfile:'',
        filelist:'',
        remindCanNotSub:false
			}
		}
  }
  componentDidMount() {
 }

  componentWillReceiveProps(nextProps) {
		if(nextProps.visible ){
			let p1 = WeaTools.callApi('/api/workplan/type/getSelectType', 'POST', {showAll:0})
			let p2 = WeaTools.callApi('/api/workplan/base/getBaseData', 'POST', {selectUser:''})
			Promise.all([p1, p2]).then((result) => {
				let remindType = [];
				if (result[1].remindTypes && result[1].remindTypes.length > 0) {
					result[1].remindTypes.map((element)=>{//check框数据
						if (element.isdefault == '1') { remindType.push(element.id)  }	
					});
				}
				let {params} = this.state;
				this.setState({
					optionsWorkPlanType:result[0],
					remindTypes:result[1].remindTypes,
          params:{...params,remindType:remindType},
          isOpenSecret:result[1].isOpenSecret,
          secretLevelOption:result[1].secretLevelOption,
          showChk:result[1].showChk
				});
			})
		}
  }

  componentWillUnmount() {
	  //组件卸载时一般清理一些状态
	  // const { coworkCollectStore } = this.props;

	  // coworkCollectStore.setShowSearchAd(false);
	  // coworkCollectStore.saveSearchParamsFields();
  }


  getRightMenu = () => {
    //const { planModulStore } = this.props;
    //let {saveLoading}=this.props.myWorkPlanStore;
    
    let btnArr = [];
    btnArr.push({
      key: 'import',
      content: getLabel(32935,'导入'),
      icon: <i className='icon-coms-export' />,
      onClick: key => this.doImport(),
    },{
      key: 'close',
      content: getLabel(309,'关闭'),
      icon: <i className='icon-coms02-Delete' />,
     onClick: key => this.doClose(),
    })
    
    return btnArr;
  }

  
  render() {
	let {visible} = this.props
	let {optionsWorkPlanType,remindTypes,params,spinning,secretLevelOption,isOpenSecret,showChk} = this.state;
		let {remindType,
			remindBeforeStart,
			remindDateBeforeStart,
			remindTimeBeforeStart,
			remindBeforeEnd,
			remindDateBeforeEnd,
			remindTimeBeforeEnd,
      workPlanType,
      secretLevel,
			validateType,
      filelist,
      remindCanNotSub

		} = params;
		let remindTypeOptions = remindTypes.map((element)=>{//check框数据
			let copy = {...element,value:element.id}
			return copy
		});
		let optionsValidateType = [
      {key: 'lastname', showname: getLabel(25034,'姓名')},
      {key: 'id', showname: getLabel(128556,'人员id')},
      {key: 'loginid', showname: getLabel(412,'登录名')},
      {key: 'workcode', showname: getLabel(20120,'工作编号')},
      {key: 'mobile', showname: getLabel(22482,'手机号码')},
      {key: 'email', showname: getLabel(20869,'邮箱')}
    ]
		let resource = {
			attach:{
				category:'32',//目录不需要
				maxSize:'5',
				uploadUrl:'/api/workplan/calendar/importExcel',
			}
		};

		let leftCol = 6, rightCol = 16;
		return (
			
			<div className="workPlan-import" id="workPlan-import-id">
			  
				<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@ee3gkd`}
					visible={visible}
					title={getLabel(384890,'导入日程')}
					icon="icon-coms-schedule"
					iconBgcolor="#7734FF"
					className="createWorkPlan"
					buttons={this.getButton()}
					style={{width:'785px',height:'504px'}}
					hasScroll={true}
					onCancel={this.doClose}
			  >
				<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@bn4l9a`} 
					datas={this.getRightMenu()}
					collectParams={{
					favname: getLabel(384890,'导入日程'),
					favouritetype: 2,
					objid: 0,
					importantlevel: 1,
					}}
					>

				
				<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@lnuqo5`} spinning={spinning} >
				<Collapse ecId={`${this && this.props && this.props.ecId || ''}_Collapse@770cec`}
					title = {getLabel(81711,'基本信息')}
					showGroup = {true}
				>
					
					<div className="workPlan-import-group">
						<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@zeemp7`} className="group-workPlanType" style={{marginBottom:'10px'}}>
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ce3nlb`} span={leftCol} style={{paddingLeft:'40px',lineHeight:'28px'}}>
								<span>{getLabel(16094,'日程类型')} :</span>
							</Col>
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3xxutt`} span={rightCol} style={{marginLeft:'43px'}}>
								<WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@ozmytg`}
									options={optionsWorkPlanType}
									value = {workPlanType}
									style = {{width:'110px'}}
									onChange={(value)=>this.onChange(value,'workPlanType')}
								/>
							</Col>
						</Row>
            {isOpenSecret&&<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@vazh8i`} className="group-workPlanType" style={{marginBottom:'10px'}}>
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@rtzjrl`} span={leftCol} style={{paddingLeft:'40px',lineHeight:'28px'}}>
								<span>{getLabel(500520,'密级')} :</span>
							</Col>
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@jhnfqj`} span={rightCol} style={{marginLeft:'43px'}}>
								<WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@bbs5ah`}
									options={secretLevelOption}
									value = {secretLevel}
									style = {{width:'110px'}}
									onChange={(value)=>this.onChange(value,'secretLevel')}
								/>
							</Col>
						</Row>}
						<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@4mi1kq`} className="group-planName" style={{marginBottom:'10px'}}>
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@miiupf`} span={leftCol} style={{paddingLeft:'40px',lineHeight:'28px'}}>
								<span>{getLabel(24638,'重复验证字段')} :</span>
							</Col>
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@pe00jb`} span={rightCol} style={{marginLeft:'43px'}}>
							<WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@mejo9e`}
									options={optionsValidateType}
									value = {validateType}
									style = {{width:'110px'}}
									onChange={(value)=>this.onChange(value,'validateType')}
								/>
							</Col>
						</Row>
            {showChk&&<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ly0exb`} className="group-workPlanType" style={{marginBottom:'10px'}}>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@m4gsjh`} span={leftCol} style={{paddingLeft:'40px',lineHeight:'28px'}}>
              <span>{getLabel(504251,'日程冲突提醒')} :</span>
            </Col>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@02s09f`} span={rightCol} style={{marginLeft:'43px'}}>
            <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@tyvxao`} checked={remindCanNotSub} onChange={(value)=>this.onChange(value,'remindCanNotSub')} />
                  <span>{getLabel(507915,'仅提醒不做处理时禁止导入')}</span>
            </Col>
            </Row>}
						{remindTypes && remindTypes.length>0 && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@h9fmi6`} className="group-remindType" style={{marginBottom:'10px',height:'28px',lineHeight:'28px'}}>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@p68dad`} span={leftCol} style={{paddingLeft:'40px'}}>
									<span>{getLabel(19781,'日程提醒方式')} :</span>
                </Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@peqjzu`} span={rightCol} style={{marginLeft:'43px'}}>
                  <CheckboxGroup ecId={`${this && this.props && this.props.ecId || ''}_CheckboxGroup@3c7cpv`} options={remindTypeOptions} value={remindType} onChange={(value)=>this.onChangeRemind(value,'remindType')} />
                </Col>
              </Row>}
              {remindType && (remindType.length>1 || (remindType.length==1&&remindType[0]!='')) && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@jngura`} className="group-remindTime" style={{marginBottom:'10px'}}>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@8iutgr`} span={leftCol} style={{paddingLeft:'40px'}}>
									<span>{getLabel(19783,'日程提醒时间')} :</span>
                </Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4jq9na`} span={rightCol} style={{marginLeft:'43px'}}>
				 <div>
                  <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@eofuq6`} checked={remindBeforeStart} onChange={(value)=>this.onChange(value,'remindBeforeStart')} />
                  <span>{getLabel(19784,'开始前')}</span>
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@011g6d`} value={remindDateBeforeStart} onChange={(value)=>this.onChange(value,'remindDateBeforeStart')} style={{width:'50px'}}/>
                  <span style={{ margin: '0 4px' }}>{getLabel(391,'小时')}</span>
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@gpg7s4`} value={remindTimeBeforeStart} onChange={(value)=>this.onChange(value,'remindTimeBeforeStart')} style={{width:'50px'}}/>
                  <span style={{ margin: '0 0 0 4px' }}>{getLabel(15049,'分钟')}</span>
                 </div>
				 <div style={{marginTop: "5px"}}> 
				  <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@tw1csv`} checked={remindBeforeEnd} onChange={(value)=>this.onChange(value,'remindBeforeEnd')} />
                  <span>{getLabel(19785,'结束前')}</span>
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@5hkypr`}  value={remindDateBeforeEnd} onChange={(value)=>this.onChange(value,'remindDateBeforeEnd')} style={{width:'50px'}}/>
                  <span style={{ margin: '0 4px' }}>{getLabel(391,'小时')}</span>
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@qfri2y`} value={remindTimeBeforeEnd} onChange={(value)=>this.onChange(value,'remindTimeBeforeEnd')} style={{width:'50px'}}/>
                  <span style={{ margin: '0 0 0 4px' }}>{getLabel(15049,'分钟')}</span>
				  </div>
                </Col>
              </Row>
              }




						<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@upu1a3`} className="group-excel"style={{marginBottom:'10px'}}>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@6228t3`} span={leftCol} style={{paddingLeft:'40px',lineHeight:'28px'}}>{getLabel(16699,'Excel文件')} :
              </Col>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zsskof`} span = {11} style={{marginLeft:'43px',marginTop:'3px'}} >
			  <div style={{ float: 'left', marginTop: -10 }}>
                    <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@p95r0v`}
                        uploadUrl='/api/workplan/calendar/addExcelFileid'
                        category='string'
                        limitType='xls'
                        maxFilesNumber={1}
						datas={filelist}
						onChange = {
							(ids, list) => {
								this.setFileId(ids, list)
							}
						} >
									<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@00m95w`}>{getLabel(125333, '选择文件')}</Button>
								</WeaUpload>
							</div>
							<div style={{ float: 'left', paddingLeft: 10 }}>
								{filelist.length == 0 ? <p>{getLabel(384040, '未选择任何文件')}</p> : filelist.map(file => <p>{file.filename}</p>)}
							</div>
              </Col>
						</Row>
						<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@6e5pcp`} className="group-download" style={{marginBottom:'10px',lineHeight:'20px'}}>
								<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@lv5njv`} span={leftCol} style={{paddingLeft:'40px'}}>
									<span>{getLabel(32205,'模版文件')} :</span>
								</Col>
								<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@7ei398`} span={rightCol} style={{marginLeft:'43px'}}>
								<a href='/workplan/config/import/workplanexcel.xls'>{getLabel(384924,'下载模版')}</a>
								<span style={{paddingLeft:'10px'}}>{getLabel(384923,'请下载模版文件，填入数据后导入!')}</span>
								</Col>
							</Row>
					</div>
					
				</Collapse>
				<Collapse ecId={`${this && this.props && this.props.ecId || ''}_Collapse@zlbn0e`}
				  title = {getLabel(25734,'说明')}
					showGroup = {true}
				>
					<p style={{padding:'10px 0 0 40px'}}>1.{getLabel(33964,'导入操作者默认为日程创建人,接收人不填写默认为创建人')}</p>

					<p style={{padding:'10px 0 0 40px'}}>2.{getLabel(33965,'如果导入数据过多导入可能需要较长时间，请不要\'刷新\'或\'关闭窗口\'')}</p>

					<p style={{padding:'10px 40px 0 40px'}}>3.{getLabel(130167,'重复验证字段说明：选择“姓名(lastname)”时，模板中的接收人字段需要填写人员姓名，选择“人员id(id)”时，模板中的接收人字段需要填写人员id，选择“登录名(loginid)”时，模板中的接收人字段需要填写人员登录名，选择“员工编号(workcode)”时，模板中的接收人字段需要填写员工编号。')} </p>
				</Collapse>
				</Spin>
				</WeaRightMenu>
				</WeaDialog>
				
			</div>
			
    )
	}

	setFileId(ids, list) {
		let {params,hasUpload} = this.state;
		let {addExcelFileid}=this.props.myWorkPlanStore;
		let {excelfile,filelist} = params
		excelfile = ids;
		filelist = list;
		params = {...params,excelfile:excelfile,filelist:filelist}
		hasUpload=true;
		this.setState({params:params})
		this.setHasUpload();
		// addExcelFileid({fileid:ids[0]},this.setHasUpload)
	}
	
	setHasUpload= (bol=true)=>{
		this.setState({hasUpload:bol})
	}

	getButton = ()=>{
		let {saveLoading}=this.props.myWorkPlanStore;
		let buttonsCreate = [
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mqjfyq@doImport`} type="primary" loading={saveLoading} disabled={false} onClick={()=>{this.doImport()}}>{getLabel(32935,'导入')}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gqw6au@doClose`} type="primary" disabled={false} onClick={()=>{this.doClose()}}>{getLabel(309,'关闭')}</Button>),
		];
		return buttonsCreate;
	}
	doClose = ()=>{
		this.props.doClose && this.props.doClose()
	}
	onChange = (values,type)=>{
		let {params} = this.state;
    if(typeof(values)==='string'){
      params = {...params,[type]:values}
      if(type=="remindDateBeforeEnd"||type=="remindDateBeforeStart"||type=="remindTimeBeforeEnd"||type=="remindTimeBeforeStart"){
        if(values<0){params = {...params,[type]:0}}
      }
    }else if(typeof(values)==='object'){
      if(values.target.type == 'radio'){
        params = {...params,[type]:values.target.value}
      }
      if(values.target.type == 'checkbox'){
        params = {...params,[type]:values.target.checked}
      }
		}
    this.setState({params:params})
	}
	onChangeRemind=(checkedValue,type)=>{
    let {params} = this.state;
    let checked = checkedValue.length>0?true:false;
    params = {...params,[type]:checkedValue}
    this.setState({params:params})
  }
	doImport = ()=>{
		const {doInit} =this.props
		let {params,hasUpload} = this.state;
		let{remindType,remindBeforeStart,remindBeforeEnd} = params;
		if(remindType.length > 0 && (remindBeforeStart === false && remindBeforeEnd === false)){
			Modal.warning({
			  title: `${getLabel(127354,'警告')}`,
			  content: `${getLabel(20238,'日程提醒时间未被选定！')}`,
			});
			return
		  }
		if(!hasUpload){
			Modal.warning({
				title: getLabel(127354,'警告'),
				content: getLabel(384922,'未选择Excel文件'),
			});
			return;
    }
		let {setSaveLoading,doExcelImport}=this.props.myWorkPlanStore;
		hasUpload && (setSaveLoading(true))
    hasUpload && this.setState({spinning:true})
    params = {...params,from:'workplan',needCheck:'1'}
		let resultDate = doExcelImport(params);
		resultDate.then(data => {
      let _this = this;
      let cont = (data&&data.message&&<div style={{marginRight: '-20px'}}>
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@6jxpva`} height='80px'>
          <div dangerouslySetInnerHTML={{__html:`${data.message}${data&&data.conflictMsg?data.conflictMsg:''}`}}/>
        </WeaNewScroll>
			</div>)
			data.flag && doInit && doInit();
			data.flag && Modal.confirm({
				title: getLabel(25750,'导入成功'),
				content: cont,
				onOk() {
					_this.doRefresh();
					setSaveLoading(false)
					_this.setState({spinning:false})
					_this.doClose();
				},
				onCancel() {
					_this.doRefresh();
					setSaveLoading(false)
					_this.setState({spinning:false})
					
				},
			});
			!data.flag && Modal.confirm({
				title: getLabel(24945,'导入失败'),
				content: cont,
				onOk() {
					_this.doRefresh();
					setSaveLoading(false)
					_this.setState({spinning:false})
					
				},
				onCancel() {
					_this.doRefresh();
					setSaveLoading(false)
					_this.setState({spinning:false})
					
				},
			});
			//上传附件之后不管成不成功,都将上传的附件不管是前端还是后端的imagefieldid,都给清空,
			//因为成功后不需要再次上传,失败后要重新检查再上传
			let {params} = _this.state;
			params = {...params,excelfile:'',filelist:''}
			hasUpload=true;
			_this.setState({params:params})

		})
		
	}

	doRefresh = ()=>{
		let {status,doUpdateCalender,changeGetCalendarData} = this.props.myWorkPlanStore
		let {workPlanShow} = toJS(status);
		workPlanShow == 'calender' && doUpdateCalender(true);
		workPlanShow == 'list' && changeGetCalendarData();
	}

}

export default WorkPlanImport

